package com.gitee.loyo.spring

import com.gitee.loyo.act.TUserModel
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner
import javax.sql.DataSource

@RunWith(SpringRunner::class)
@SpringBootTest(
    classes = [SpringTestApplication::class],
)
class SpringTest {

    @Autowired
    lateinit var dataSource: DataSource
    @Autowired
    lateinit var testService: TestService
    lateinit var testTransactionService: TestTransactionService

    @Before
    fun start(){
        dataSource.connection.use { conn->
                conn.createStatement().use {
                    it.executeUpdate("""
                            CREATE TABLE IF NOT EXISTS t_user(
                                user_id bigint AUTO_INCREMENT NOT NULL primary key,
                                user_name varchar(100) NOT NULL,
                                sex int(1) NOT NULL,
                                active tinyint NOT NULL DEFAULT 1
                            )
                        """.trimIndent())
                }
        }
    }

    @After
    fun end(){
        dataSource.connection.use { conn ->
            conn.createStatement().use {
                it.execute("truncate table t_user")
            }
            conn.commit()
        }
    }

    @Test
    fun testService(){
        val user = testService.createUser()
        Assert.assertEquals(user, TUserModel.findByID(1))
    }

    @Test
    fun testServiceTransactional(){
        try{
            testTransactionService.failToCreateUsers()
        }catch (e: Exception){}
        Assert.assertEquals(0, TUserModel.count())
    }

    @Test
    fun testServiceTransactional2(){
        try{
            testService.tryCreateUsers()
        }catch (e: Exception){}
        Assert.assertEquals(1, TUserModel.count())
    }

    @Test
    fun testServiceTransactional3(){
        try{
            testService.createUsersWithNest()
        }catch (e: Exception){}
        Assert.assertEquals(0, TUserModel.count())
    }

    @Test
    fun testServiceTransactional4(){
        try{
            testService.createUsersWithNever()
        }catch (e: Exception){}
        Assert.assertEquals(0, TUserModel.count())
    }

    @Test
    fun testServiceTransactional5(){
        try{
            testService.createUsersWithNew()
        }catch (e: Exception){}
        Assert.assertEquals(2, TUserModel.count())
    }
}